//
//  WBHomeViewModel.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/3.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
import SDWebImage
class WBHomeViewModel: NSObject {
    var statusArray : [WBStatusViewModel]?
    func loadData(isPullUp:Bool,completion:@escaping (Bool,Int)->())
    {
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        var maxId : Int64 = 0
        var sinceId : Int64 = 0
        if isPullUp{
            if let id = statusArray?.last?.status?.id{
                maxId = id - 1
            }
        }else
        {
            if let id = statusArray?.first?.status?.id{
                sinceId = id
            }
        }
        let parameters = [
            
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)",
        "access_token":WBUserAccountViewModel.sharedModel.account?.access_token ?? ""
        ]
        
        WBNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: parameters) { (responce, error) in
            if error != nil
            {
                print("请求错误：\(error)")
                completion(false,0)
                return
            }
            
            //print(responce!)
            guard let dictArray = (responce! as! [String:Any])["statuses"] as? [[String : Any]] else
            {
                return
            }
            let modelArr = NSArray.yy_modelArray(with: WBStatus.classForCoder(), json: dictArray) as? [WBStatus]
            var tempArr = [WBStatusViewModel]()
            for status in modelArr!
            {
//                if let pic_urls = status.pic_urls,pic_urls.count > 0
//                {
//                    print(pic_urls.first?.thumbnail_pic ?? "")
//                }
                
                let viewModel = WBStatusViewModel()
                viewModel.status = status
                tempArr.append(viewModel)
            }
            
            if self.statusArray == nil{
                self.statusArray = [WBStatusViewModel]()
            }
            if isPullUp{
                self.statusArray = self.statusArray! + tempArr
            }else
            {
                self.statusArray = tempArr + self.statusArray!
            }

            //self.statusArray = tempArr
            self.cacheSinglePicture(status: tempArr, completion: completion)
            //completion(true)
        }
    }

    private func cacheSinglePicture(status:[WBStatusViewModel],completion:@escaping (Bool,Int)->()){
        
        let group = DispatchGroup.init()
        for value in status
        {
            guard let pic_urls = (value.status?.pic_urls?.count == 1) ? value.status?.pic_urls : value.status?.retweeted_status?.pic_urls,pic_urls.count == 1 else {
            continue
            }
            let photoInfo = pic_urls.first!
            let urlString = photoInfo.thumbnail_pic
            let url = URL(string: urlString ?? "")
            group.enter()
            SDWebImageDownloader.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _) in
                photoInfo.size = image?.size
                group.leave()
            })
        }
        group.notify(queue: DispatchQueue.main) { 
            completion(true,status.count)
        }
    }
}
